<template>
  <div class="detail-page">
    <el-page-header content="销售退货单详情" @back="handleBack" class="detail-header" />

    <!-- 基础信息卡片 -->
    <el-card class="detail-card info-card" shadow="never">
      <!-- 顶部标题和操作区域 -->
      <div class="header-section">
        <div class="title-area">
          <span class="order-label">销售退货单号:</span>
          <span class="order-number">{{ saleReturnsForm.saleReturnsNo || '--' }}</span>
          <el-tag :type="getStatusTagType(saleReturnsForm.saleReturnsStatus)" size="default" class="status-tag">
            {{ getStatusText(saleReturnsForm.saleReturnsStatus) }}
          </el-tag>
        </div>
        <div class="action-buttons">
          <el-button type="primary" @click="handleEdit" size="small">编辑</el-button>
          <el-button type="danger" @click="handleDelete" size="small">删除</el-button>
          <el-button type="warning" @click="handleAudit" size="small">审核</el-button>
          <el-button @click="handleClose" size="small">关闭</el-button>
          <el-button @click="handleCopy" size="small">复制</el-button>
          <el-button @click="handlePrint" size="small">打印</el-button>
        </div>
      </div>

      <!-- 基础信息 -->
      <div class="info-content">
        <el-descriptions :column="4" border>
          <el-descriptions-item label="制单人">
            <span class="info-value">{{ saleReturnsForm.createor || saleReturnsForm.creator || '-' }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="所在部门">
            <span class="info-value">{{ saleReturnsForm.organizationName || saleReturnsForm.saleReturnsDepartment || '-' }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="制单时间">
            <span class="info-value">{{ formatDateTime(saleReturnsForm.saleReturnsTime || saleReturnsForm.createrTime) }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="退货日期">
            <span class="info-value">{{ formatDate(saleReturnsForm.saleReturnsDate) }}</span>
          </el-descriptions-item>
        </el-descriptions>

        <el-descriptions :column="3" border class="info-row">
          <el-descriptions-item label="销售单号">
            <span class="info-value">{{ saleReturnsForm.salesOrderNo || '-' }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="客户名称">
            <span class="info-value">{{ saleReturnsForm.customerName || '-' }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="联系人">
            <span class="info-value">{{ saleReturnsForm.contactName || saleReturnsForm.saleReturnsContact || '-' }}</span>
          </el-descriptions-item>
        </el-descriptions>

        <el-descriptions :column="3" border class="info-row">
          <el-descriptions-item label="联系方式">
            <span class="info-value">{{ saleReturnsForm.contactPhone || saleReturnsForm.saleReturnsContactPhone || '-' }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="销售部门">
            <span class="info-value">{{ saleReturnsForm.salesDepartment || saleReturnsForm.saleReturnsDepartment || '-' }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="销售负责人">
            <span class="info-value">{{ saleReturnsForm.salesOwner || saleReturnsForm.saleReturnsUser || '-' }}</span>
          </el-descriptions-item>
        </el-descriptions>

        <el-descriptions :column="2" border class="info-row">
          <el-descriptions-item label="退货原因">
            <span class="info-value">{{ saleReturnsForm.saleReturnReason || '-' }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="备注">
            <span class="info-value">{{ saleReturnsForm.remark || saleReturnsForm.saleReturnsRemark || '-' }}</span>
          </el-descriptions-item>
        </el-descriptions>
      </div>
    </el-card>

    <!-- 标签页卡片 -->
    <el-card class="detail-card tabs-card" shadow="never">
      <div class="tabs-section">
        <el-tabs v-model="activeTab" type="card" class="detail-tabs" @tab-change="handleTabChange">
          <!-- 其他信息 -->
          <el-tab-pane label="其他信息" name="other">
            <div class="tab-content">
              <div class="section-block">
                <div class="section-title">附件</div>
                <div class="attachment-list" v-if="fileList.length > 0">
                  <el-link
                    v-for="(file, index) in fileList"
                    :key="index"
                    type="primary"
                    :href="file.url"
                    target="_blank"
                    class="file-link"
                  >
                    <el-icon><Document /></el-icon>
                    {{ file.name }}
                  </el-link>
                </div>
                <div v-else class="empty-attachment">
                  <el-icon class="attachment-icon"><Box /></el-icon>
                  <span>暂无附件</span>
                </div>
              </div>

              <div class="section-block">
                <div class="section-title">自定义字段</div>
                <el-descriptions :column="2" border>
                  <el-descriptions-item
                    v-for="(field, index) in customFields"
                    :key="index"
                    :label="field.label"
                  >
                    <span class="info-value">{{ field.value || '-' }}</span>
                  </el-descriptions-item>
                  <div v-if="customFields.length === 0" class="empty-text">暂无自定义字段</div>
                </el-descriptions>
              </div>
            </div>
          </el-tab-pane>

          <!-- 退货明细 -->
          <el-tab-pane label="退货明细" name="details">
            <div class="tab-content">
              <div class="tab-header">
                <el-button @click="handleExportDetails" size="small">导出</el-button>
              </div>
              <el-table
                :data="returnDetails"
                border
                stripe
                style="width: 100%"
                v-loading="detailLoading"
              >
                <el-table-column type="selection" width="55" />
                <el-table-column type="index" label="序号" width="60" />
                <el-table-column prop="productName" label="货品名称" min-width="140" show-overflow-tooltip />
                <el-table-column prop="productCode" label="货品编号" min-width="140" show-overflow-tooltip />
                <el-table-column prop="productTypeName" label="货品类型" min-width="120" show-overflow-tooltip />
                <el-table-column prop="specification" label="规格型号" min-width="120" show-overflow-tooltip />
                <el-table-column prop="unitName" label="单位" width="80" />
                <el-table-column prop="salesQuantity" label="销售数量" width="100" align="right">
                  <template #default="{ row }">
                    {{ row.salesQuantity ?? 0 }}
                  </template>
                </el-table-column>
                <el-table-column label="累计退货数量" width="120" align="right">
                  <template #default="{ row }">
                    {{ row.accumulatedReturnQuantity ?? row.returnQuantity ?? 0 }}
                  </template>
                </el-table-column>
                <el-table-column prop="returnQuantity" label="本次退货数量" width="120" align="right">
                  <template #default="{ row }">
                    {{ row.returnQuantity ?? 0 }}
                  </template>
                </el-table-column>
                <el-table-column label="销售单价" width="120" align="right">
                  <template #default="{ row }">
                    ¥{{ Number(row.unitPrice ?? row.salesPrice ?? 0).toFixed(2) }}
                  </template>
                </el-table-column>
                <el-table-column label="退货金额" width="120" align="right">
                  <template #default="{ row }">
                    <span class="amount-text">¥{{ Number(row.returnAmount ?? 0).toFixed(2) }}</span>
                  </template>
                </el-table-column>
              </el-table>
              <div class="detail-summary" v-if="returnDetails.length > 0">
                <span>合计</span>
                <span>退货种类: {{ returnDetails.length }}</span>
                <span>退货数量: {{ totalReturnQuantity }}</span>
                <span>退货金额: <span class="amount-text">¥{{ totalReturnAmount.toFixed(2) }}</span></span>
              </div>
            </div>
          </el-tab-pane>

          <!-- 入库记录 -->
          <el-tab-pane label="入库记录" name="inbound">
            <div class="tab-content">
              <div class="tab-header">
                <el-button @click="handleExportInbound" size="small">导出</el-button>
              </div>
              <el-table
                :data="inboundRecords"
                border
                stripe
                style="width: 100%"
                v-loading="inboundLoading"
              >
                <el-table-column type="selection" width="55" />
                <el-table-column type="index" label="序号" width="60" />
                <el-table-column prop="inboundNo" label="入库单号" min-width="160" show-overflow-tooltip />
                <el-table-column prop="inboundDate" label="入库日期" width="130">
                  <template #default="{ row }">
                    {{ formatDate(row.inboundDate) }}
                  </template>
                </el-table-column>
                <el-table-column prop="warehouseName" label="仓库名称" min-width="120" show-overflow-tooltip />
                <el-table-column prop="inboundGoods" label="入库货品" min-width="200" show-overflow-tooltip />
                <el-table-column prop="inboundQuantity" label="入库数量" width="100" align="right" />
                <el-table-column prop="inboundAmount" label="入库金额" width="120" align="right">
                  <template #default="{ row }">
                    ¥{{ Number(row.inboundAmount ?? 0).toFixed(2) }}
                  </template>
                </el-table-column>
                <el-table-column prop="handler" label="经办人" width="100" show-overflow-tooltip />
                <el-table-column prop="documentMaker" label="制单人" width="100" show-overflow-tooltip />
                <el-table-column prop="department" label="所在部门" min-width="120" show-overflow-tooltip />
                <el-table-column prop="createTime" label="制单时间" width="160">
                  <template #default="{ row }">
                    {{ formatDateTime(row.createTime) }}
                  </template>
                </el-table-column>
              </el-table>
              <div class="detail-summary" v-if="inboundRecords.length > 0">
                <span>合计</span>
                <span>入库种类数: {{ inboundRecords.length }}</span>
                <span>入库数量: {{ totalInboundQuantity }}</span>
                <span>入库金额: <span class="amount-text">¥{{ totalInboundAmount.toFixed(2) }}</span></span>
              </div>
              <div v-else class="empty-text">暂无入库记录</div>
            </div>
          </el-tab-pane>

          <!-- 操作记录 -->
          <el-tab-pane label="操作记录" name="operation">
            <div class="tab-content">
              <div class="tab-header">
                <el-form :model="operationSearchForm" :inline="true" class="search-form">
                  <el-form-item label="操作类型">
                    <el-select v-model="operationSearchForm.operationType" placeholder="请选择" clearable style="width: 150px">
                      <el-option label="新增" value="新增" />
                      <el-option label="修改" value="修改" />
                      <el-option label="删除" value="删除" />
                      <el-option label="暂存" value="暂存" />
                      <el-option label="审核" value="审核" />
                      <el-option label="导出" value="导出" />
                      <el-option label="打印" value="打印" />
                      <el-option label="提交单据" value="提交单据" />
                      <el-option label="撤销审核" value="撤销审核" />
                      <el-option label="关闭单据" value="关闭单据" />
                    </el-select>
                  </el-form-item>
                  <el-form-item label="操作人">
                    <el-input v-model="operationSearchForm.operator" placeholder="请输入" clearable style="width: 150px" />
                  </el-form-item>
                  <el-form-item label="操作时间">
                    <el-date-picker
                      v-model="operationSearchForm.operationTime"
                      type="daterange"
                      range-separator="至"
                      start-placeholder="开始日期"
                      end-placeholder="结束日期"
                      value-format="YYYY-MM-DD"
                      clearable
                      style="width: 240px"
                    />
                  </el-form-item>
                  <el-form-item>
                    <el-button type="primary" @click="handleOperationQuery">查询</el-button>
                    <el-button @click="handleOperationReset">重置</el-button>
                  </el-form-item>
                </el-form>
                <el-button @click="handleExportOperation" size="small">导出</el-button>
              </div>
              <el-table
                :data="operationRecords"
                border
                stripe
                style="width: 100%"
                v-loading="operationLoading"
              >
                <el-table-column type="selection" width="55" />
                <el-table-column type="index" label="序号" width="60" />
                <el-table-column prop="operator" label="操作人" width="120" show-overflow-tooltip />
                <el-table-column prop="operationType" label="操作类型" width="120" />
                <el-table-column prop="operationContent" label="操作内容描述" min-width="200" show-overflow-tooltip />
                <el-table-column prop="creator" label="制单人" width="120" show-overflow-tooltip>
                  <template #default="{ row }">
                    {{ row.creator || saleReturnsForm.createor || '-' }}
                  </template>
                </el-table-column>
                <el-table-column prop="operationTime" label="操作时间" width="160">
                  <template #default="{ row }">
                    {{ formatDateTime(row.operationTime) }}
                  </template>
                </el-table-column>
              </el-table>
              <div class="pagination-wrapper" v-if="operationRecords.length > 0">
                <el-pagination
                  v-model:current-page="operationPagination.pageindex"
                  v-model:page-size="operationPagination.pagesize"
                  :total="operationPagination.total"
                  :page-sizes="[10, 20, 50, 100]"
                  layout="total, sizes, prev, pager, next"
                  @size-change="handleOperationSizeChange"
                  @current-change="handleOperationPageChange"
                />
              </div>
              <div v-else class="empty-text">暂无操作记录</div>
            </div>
          </el-tab-pane>

          <!-- 审核记录 -->
          <el-tab-pane label="审核记录" name="approval">
            <div class="tab-content">
              <el-table
                :data="approvalRecords"
                border
                stripe
                style="width: 100%"
                v-loading="approvalLoading"
              >
                <el-table-column type="index" label="序号" width="60" />
                <el-table-column prop="operationType" label="操作类型" width="120" />
                <el-table-column prop="approvalResult" label="审核结果" width="120">
                  <template #default="{ row }">
                    <el-tag
                      v-if="row.approvalResult"
                      :type="row.approvalResult === '通过' ? 'success' : 'danger'"
                      size="small"
                    >
                      {{ row.approvalResult }}
                    </el-tag>
                    <span v-else>-</span>
                  </template>
                </el-table-column>
                <el-table-column prop="approvalComment" label="审核意见" min-width="200" show-overflow-tooltip />
                <el-table-column prop="operator" label="操作人" width="120" show-overflow-tooltip />
                <el-table-column prop="operationTime" label="操作时间" width="160">
                  <template #default="{ row }">
                    {{ formatDateTime(row.operationTime) }}
                  </template>
                </el-table-column>
              </el-table>
              <div v-if="approvalRecords.length === 0" class="empty-text">暂无审核记录</div>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </el-card>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Document, Box } from '@element-plus/icons-vue'
import moment from 'moment'
import myaxios from '@/http/MyAxios'

const route = useRoute()
const router = useRouter()

// 表单数据
const saleReturnsForm = reactive({
  saleReturnsId: '',
  saleReturnsNo: '',
  saleReturnsDate: '',
  saleReturnsStatus: 0,
  salesOrderId: '',
  salesOrderNo: '',
  customerId: '',
  customerName: '',
  contactName: '',
  contactPhone: '',
  salesDepartment: '',
  salesOwner: '',
  saleReturnReason: '',
  remark: '',
  saleReturnsContact: '',
  saleReturnsContactPhone: '',
  saleReturnsDepartment: '',
  saleReturnsUser: '',
  saleReturnsRemark: '',
  createrTime: '',
  saleReturnsTime: '',
  createor: '',
  creator: '',
  organizationName: '',
})

// 退货明细
const returnDetails = ref<any[]>([])
const detailLoading = ref(false)

// 附件列表
const fileList = ref<Array<{ name: string; url: string }>>([])

// 自定义字段
const customFields = ref<Array<{ label: string; value: string }>>([
  { label: '自定义字段1', value: '' },
  { label: '自定义字段2', value: '' },
  { label: '自定义字段3', value: '' },
  { label: '自定义字段4', value: '' },
  { label: '自定义字段5', value: '' },
])

// 标签页
const activeTab = ref('other')

// 入库记录
const inboundRecords = ref<any[]>([])
const inboundLoading = ref(false)
const inboundLoaded = ref(false)

// 操作记录
const operationRecords = ref<any[]>([])
const operationLoading = ref(false)
const operationSearchForm = reactive({
  operationType: '',
  operator: '',
  operationTime: [] as string[],
})
const operationPagination = reactive({
  pageindex: 1,
  pagesize: 10,
  total: 0,
})
const operationLoaded = ref(false)

// 原始详情数据（用于解析关联记录）
const rawDetailData = ref<any>(null)

// 审核记录
const approvalRecords = ref<any[]>([])
const approvalLoading = ref(false)

// 计算属性
const totalReturnQuantity = computed(() => {
  return returnDetails.value.reduce((sum, item) => sum + Number(item.returnQuantity || 0), 0)
})

const totalReturnAmount = computed(() => {
  return returnDetails.value.reduce((sum, item) => sum + Number(item.returnAmount || 0), 0)
})

const totalInboundQuantity = computed(() => {
  return inboundRecords.value.reduce((sum, item) => sum + Number(item.inboundQuantity || 0), 0)
})

const totalInboundAmount = computed(() => {
  return inboundRecords.value.reduce((sum, item) => sum + Number(item.inboundAmount || 0), 0)
})

// 通用工具
const tryParseJson = (value: any) => {
  if (typeof value !== 'string') return value
  try {
    return JSON.parse(value)
  } catch (error) {
    return value
  }
}

const normalizeList = (payload: any): any[] => {
  if (!payload) return []
  if (Array.isArray(payload)) return payload
  const parsed = tryParseJson(payload)
  if (Array.isArray(parsed)) return parsed
  if (typeof parsed !== 'object' || parsed === null) return []
  const candidateKeys = ['data', 'records', 'list', 'items', 'rows', 'detailList', 'Details', 'Data']
  for (const key of candidateKeys) {
    if (Array.isArray(parsed?.[key])) return parsed[key]
  }
  if (Array.isArray(parsed?.pages?.data)) return parsed.pages.data
  return []
}

const extractRecordsFromSource = (source: any, keys: string[]): any[] => {
  if (!source) return []
  for (const key of keys) {
    if (source[key] !== undefined) {
      const list = normalizeList(source[key])
      if (list.length) return list
    }
  }
  return []
}

const getRecordsFromRaw = (keys: string[]): any[] => {
  const candidates = [
    rawDetailData.value,
    rawDetailData.value?.saleReturns,
    rawDetailData.value?.detail,
    rawDetailData.value?.data,
    rawDetailData.value?.baseInfo,
  ]
  for (const candidate of candidates) {
    const list = extractRecordsFromSource(candidate, keys)
    if (list.length) return list
  }
  return []
}

const pickFirst = (source: Record<string, any> | null | undefined, keys: string[], defaultValue: any = '') => {
  if (!source) return defaultValue
  for (const key of keys) {
    if (key in source && source[key] !== undefined && source[key] !== null && source[key] !== '') {
      return source[key]
    }
  }
  return defaultValue
}

const matchesCurrentSaleReturn = (record: any) => {
  if (!record) return false
  const currentId = saleReturnsForm.saleReturnsId ? String(saleReturnsForm.saleReturnsId) : ''
  const currentNo = saleReturnsForm.saleReturnsNo ? String(saleReturnsForm.saleReturnsNo) : ''
  const idCandidates = [
    record.saleReturnsId,
    record.saleReturnsID,
    record.sourceId,
    record.documentId,
    record.businessId,
    record.relatedId,
    record.refId,
  ]
  const noCandidates = [
    record.saleReturnsNo,
    record.documentCode,
    record.referenceNo,
    record.returnNo,
    record.orderNo,
  ]
  if (currentId && idCandidates.some((val) => val !== undefined && val !== null && String(val) === currentId)) {
    return true
  }
  if (currentNo && noCandidates.some((val) => val && String(val) === currentNo)) {
    return true
  }
  const content = record.operationContent || record.remark || record.description || ''
  return Boolean(currentNo && typeof content === 'string' && content.includes(currentNo))
}

const buildCleanParams = (params: Record<string, any>) => {
  const result: Record<string, any> = {}
  Object.keys(params).forEach((key) => {
    const value = params[key]
    if (value !== undefined && value !== null && value !== '') {
      result[key] = value
    }
  })
  return result
}

const extractGoodsNames = (record: any) => {
  const candidateArrays = [
    record.goodsDetails,
    record.returnDetails,
    record.inboundDetails,
    record.items,
    record.detailList,
  ]
  for (const candidate of candidateArrays) {
    const list = normalizeList(candidate)
    if (list.length) {
      const names = list
        .map((item: any) => item?.productName || item?.goodsName || item?.productCode)
        .filter(Boolean)
      if (names.length) return names.join('，')
    }
  }
  const textCandidates = [
    record.inboundGoods,
    record.saleReturnsGoodsText,
    record.goodsNames,
    record.goodsList,
    record.productNames,
    record.remark,
  ]
  return pickFirst(record, textCandidates as any, '') || ''
}

const mapInboundRecord = (item: any) => ({
  inboundNo: pickFirst(item, ['inboundNo', 'inboundCode', 'stockinCode', 'documentCode', 'orderNo'], '-'),
  inboundDate: pickFirst(item, ['inboundDate', 'stockinDate', 'createTime', 'documentCreation']),
  warehouseName: pickFirst(item, ['warehouseName', 'warehouse', 'stockName']),
  inboundGoods: extractGoodsNames(item),
  inboundQuantity: Number(
    pickFirst(item, ['inboundQuantity', 'quantity', 'inboundNum', 'stockinNum', 'saleReturnsQuantity'], 0),
  ),
  inboundAmount: Number(
    pickFirst(item, ['inboundAmount', 'amount', 'inboundMoney', 'totalAmount', 'saleReturnsAmount'], 0),
  ),
  handler: pickFirst(item, ['handler', 'handlerProple', 'operator', 'userName']),
  documentMaker: pickFirst(item, ['documentMaker', 'createor', 'creator', 'documentCreator', 'maker']),
  department: pickFirst(item, ['department', 'organizationName', 'deptName', 'saleReturnsDepartment']),
  createTime: pickFirst(item, ['createTime', 'documentCreation', 'inboundTime']),
})

const prefillRelatedRecordsFromRaw = () => {
  const inboundRaw = getRecordsFromRaw(['inboundRecords', 'inboundList', 'stockinRecords', 'receiptRecords'])
  if (inboundRaw.length && !inboundLoaded.value) {
    inboundRecords.value = inboundRaw.filter(matchesCurrentSaleReturn).map(mapInboundRecord)
    inboundLoaded.value = inboundRecords.value.length > 0
  }

  const operationRaw = getRecordsFromRaw(['operationRecords', 'operationLogs', 'logList', 'operateList'])
  if (operationRaw.length && !operationLoaded.value) {
    operationRecords.value = operationRaw.filter(matchesCurrentSaleReturn).map((item: any) => ({
      ...item,
      operator: item.operator || item.operateUser || item.userName || item.createUser || '',
      operationType: item.operationType || item.operateType || item.actionType || '',
      operationContent: item.operationContent || item.operateContent || item.description || '',
      creator: item.creator || item.createor || saleReturnsForm.createor || '',
      operationTime: item.operationTime || item.operateTime || item.createTime || item.createrTime || '',
    }))
    operationPagination.total = operationRecords.value.length
    operationLoaded.value = operationRecords.value.length > 0
  }
}

// 状态相关
const SALE_RETURN_STATUS = [
  { value: 0, label: '草稿', tagType: 'info' },
  { value: 1, label: '待审核', tagType: 'warning' },
  { value: 2, label: '驳回', tagType: 'danger' },
  { value: 3, label: '未入库', tagType: 'info' },
  { value: 4, label: '部分入库', tagType: 'warning' },
  { value: 5, label: '已入库', tagType: 'success' },
  { value: 6, label: '已完成', tagType: 'success' },
  { value: 7, label: '已关闭', tagType: 'danger' },
]

const getStatusText = (status: number | string) => {
  const statusNumber = Number(status)
  const option = SALE_RETURN_STATUS.find((item) => Number(item.value) === statusNumber)
  return option?.label ?? '未知'
}

const getStatusTagType = (status: number | string) => {
  const statusNumber = Number(status)
  const option = SALE_RETURN_STATUS.find((item) => Number(item.value) === statusNumber)
  return option?.tagType ?? 'info'
}

// 格式化函数
const formatDate = (date?: string) => {
  if (!date) return '--'
  return moment(date).format('YYYY-MM-DD')
}

const formatDateTime = (date?: string) => {
  if (!date) return '--'
  return moment(date).format('YYYY-MM-DD HH:mm:ss')
}

// 标签页切换
const handleTabChange = (tabName: string) => {
  if (tabName === 'details' && returnDetails.value.length === 0) {
    loadReturnDetails()
  } else if (tabName === 'inbound' && inboundRecords.value.length === 0) {
    loadInboundRecords()
  } else if (tabName === 'operation') {
    // 每次切换到操作记录标签页都重新加载，确保显示最新数据
    loadOperationRecords()
  } else if (tabName === 'approval' && approvalRecords.value.length === 0) {
    loadApprovalRecords()
  }
}

// 操作按钮
const handleBack = () => {
  router.back()
}

const handleEdit = () => {
  router.push({
    path: '/updatesalereturn',
    query: { saleReturnsId: saleReturnsForm.saleReturnsId },
  })
}

const handleDelete = () => {
  ElMessageBox.confirm('确认删除该销售退货单吗？', '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      try {
        const res = await myaxios.delete('/api/SaleReturns/DeleteSaleReturns', {
          params: { saleReturnsId: saleReturnsForm.saleReturnsId },
        })
        if (res?.data?.code === 200) {
          ElMessage.success(res?.data?.message || '删除成功')
          // 如果是逻辑删除，刷新操作记录以显示删除操作
          if (activeTab.value === 'operation') {
            await loadOperationRecords(true)
          }
          // 延迟跳转，让用户能看到操作记录更新
          setTimeout(() => {
            router.push('/getsalereturn')
          }, 1000)
        } else {
          ElMessage.error(res?.data?.message || '删除失败')
        }
      } catch (error) {
        console.error('删除销售退货单失败:', error)
        ElMessage.error('删除失败，请稍后重试')
      }
    })
    .catch(() => {})
}

const handleAudit = () => {
  ElMessage.warning('审核功能正在开发中')
}

const handleClose = () => {
  ElMessageBox.confirm('确认关闭该销售退货单吗？', '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      ElMessage.warning('关闭功能正在开发中')
    })
    .catch(() => {})
}

const handleCopy = () => {
  ElMessage.warning('复制功能正在开发中')
}

const handlePrint = () => {
  window.print()
}

// 加载销售退货单详情
const loadSaleReturnsDetail = async (id: string) => {
  try {
    const res = await myaxios.get('/api/SaleReturns/GetSaleReturnsDetail', {
      params: { saleReturnsId: id },
    })
    if (res?.data?.code === 200) {
      const data = res.data.data || {}
      rawDetailData.value = data
      Object.assign(saleReturnsForm, {
        saleReturnsId: data.saleReturnsId || data.SaleReturnsId || id,
        saleReturnsNo: data.saleReturnsNo || data.SaleReturnsNo || '',
        saleReturnsDate: data.saleReturnsDate || data.SaleReturnsDate || '',
        saleReturnsStatus: data.saleReturnsStatus || data.SaleReturnsStatus || 0,
        salesOrderId: data.salesOrderId || data.SalesOrderId || '',
        salesOrderNo: data.salesOrderNo || data.SalesOrderNo || data.orderNo || '',
        customerId: data.customerId || data.CustomerId || '',
        customerName: data.customerName || data.CustomerName || data.customer || '',
        contactName: data.contactName || data.saleReturnsContact || data.contact || '',
        contactPhone: data.contactPhone || data.saleReturnsContactPhone || data.contactMethod || '',
        salesDepartment: data.salesDepartment || data.organizationName || data.saleReturnsDepartment || '',
        salesOwner: data.salesOwner || data.userName || data.saleReturnsUser || '',
        saleReturnReason: data.saleReturnReason || data.reason || '',
        remark: data.remark || data.saleReturnsRemark || '',
        saleReturnsContact: data.saleReturnsContact || data.contactName || '',
        saleReturnsContactPhone: data.saleReturnsContactPhone || data.contactPhone || '',
        saleReturnsDepartment: data.saleReturnsDepartment || data.organizationName || '',
        saleReturnsUser: data.saleReturnsUser || data.userName || '',
        saleReturnsRemark: data.saleReturnsRemark || data.remark || '',
        createrTime: data.createrTime || data.auditTime || '',
        saleReturnsTime: data.saleReturnsTime || data.createTime || data.createrTime || '',
        createor: data.createor || data.creator || data.createUser || '',
        creator: data.creator || data.createor || data.createUser || '',
        organizationName: data.organizationName || data.departmentName || data.saleReturnsDepartment || '',
      })
      prefillRelatedRecordsFromRaw()
    } else {
      ElMessage.error(res?.data?.message || '获取销售退货单详情失败')
    }
  } catch (error) {
    console.error('获取销售退货单详情失败:', error)
    ElMessage.error('获取销售退货单详情失败，请稍后重试')
  }
}

// 加载退货明细
const loadReturnDetails = async () => {
  detailLoading.value = true
  try {
    const res = await myaxios.get('/api/SaleReturns/GetSaleReturnsDetail', {
      params: { saleReturnsId: saleReturnsForm.saleReturnsId },
    })
    if (res?.data?.code === 200) {
      const data = res.data.data || {}
      const details =
        data.saleReturnsDetails ||
        data.goodsDetails ||
        data.details ||
        data.SaleReturnsDetails ||
        data.detailList ||
        []
      returnDetails.value = details.map((item: any) => ({
        productId: item.productId || item.ProductId,
        productName: item.productName || item.ProductName || '',
        productCode: item.productCode || item.ProductCode || '',
        productTypeName: item.productTypeName || item.ProductTypeName || '',
        specification: item.specification || item.specificationModel || '',
        unitName: item.unitName || item.unit || '',
        salesQuantity: Number(item.salesQuantity || item.quantity || 0),
        accumulatedReturnQuantity: Number(item.accumulatedReturnQuantity || item.returnQuantity || 0),
        returnQuantity: Number(item.saleReturnsQuantity || item.returnQuantity || item.quantity || 0),
        unitPrice: Number(item.saleReturnsUnitPrice || item.unitPrice || item.salesPrice || 0),
        returnAmount: Number(item.saleReturnsAmount || item.returnAmount || item.amount || 0),
      }))
    }
  } catch (error) {
    console.error('获取退货明细失败:', error)
  } finally {
    detailLoading.value = false
  }
}

// 加载入库记录
const loadInboundRecords = async (force = false) => {
  if (!force && inboundLoaded.value && inboundRecords.value.length) return
  inboundLoading.value = true
  try {
    if (!force) {
      const cached = getRecordsFromRaw(['inboundRecords', 'inboundList', 'stockinRecords', 'receiptRecords'])
      if (cached.length) {
        inboundRecords.value = cached.filter(matchesCurrentSaleReturn).map(mapInboundRecord)
        inboundLoaded.value = inboundRecords.value.length > 0
        return
      }
    }

    const params = buildCleanParams({
      saleReturnsId: saleReturnsForm.saleReturnsId,
      saleReturnsNo: saleReturnsForm.saleReturnsNo,
      salesOrderId: saleReturnsForm.salesOrderId,
      customerId: saleReturnsForm.customerId,
      pageindex: 1,
      pagesize: 50,
    })

    const apiCandidates = [
      '/api/SaleReturns/GetInboundRecords',
      '/api/Inbound/GetInboundRecords',
      '/api/Inbound/GetInbound',
      '/api/Stockin/GetStockinRecords',
    ]

    let list: any[] = []
    for (const api of apiCandidates) {
      try {
        const res = await myaxios.get(api, { params })
        if (res?.data?.code === 200 || res?.data?.success) {
          const dataSection = res.data?.data || res.data
          list = normalizeList(dataSection)
          if (!list.length && Array.isArray(dataSection)) {
            list = dataSection
          }
          if (list.length) break
        }
      } catch (error) {
        console.warn(`获取入库记录接口 ${api} 失败:`, error)
      }
    }

    inboundRecords.value = list.filter(matchesCurrentSaleReturn).map(mapInboundRecord)
    inboundLoaded.value = inboundRecords.value.length > 0
  } catch (error) {
    console.error('获取入库记录失败:', error)
    inboundRecords.value = []
  } finally {
    inboundLoading.value = false
  }
}

// 加载操作记录
const loadOperationRecords = async (force = false) => {
  const hasFilters =
    !!operationSearchForm.operationType ||
    !!operationSearchForm.operator ||
    (operationSearchForm.operationTime && operationSearchForm.operationTime.length > 0)
  if (!force && operationLoaded.value && !hasFilters) return
  operationLoading.value = true
  try {
    if (!force && !hasFilters) {
      const cached = getRecordsFromRaw(['operationRecords', 'operationLogs', 'logList', 'operateList'])
      if (cached.length) {
        operationRecords.value = cached.filter(matchesCurrentSaleReturn).map((item: any) => ({
          ...item,
          creator: item.creator || item.createor || item.documentMaker || item.maker || saleReturnsForm.createor || '',
          operator: item.operator || item.operateUser || item.userName || item.createUser || item.operateUserName || '',
          operationType: item.operationType || item.operateType || item.actionType || item.type || '',
          operationContent: item.operationContent || item.operateContent || item.actionDescription || item.description || item.content || '',
          operationTime: item.operationTime || item.operateTime || item.createTime || item.createrTime || item.operateDate || item.updateTime || '',
        }))
        operationPagination.total = operationRecords.value.length
        operationLoaded.value = operationRecords.value.length > 0
        return
      }
    }

    const params: any = {
      saleReturnsId: saleReturnsForm.saleReturnsId,
      documentId: saleReturnsForm.saleReturnsId,
      businessId: saleReturnsForm.saleReturnsId,
      relatedId: saleReturnsForm.saleReturnsId,
      moduleCode: 'SaleReturns',
      moduleName: '销售退货',
      businessType: 'SaleReturns',
      documentType: 'SaleReturns',
      saleReturnsNo: saleReturnsForm.saleReturnsNo,
      pageindex: operationPagination.pageindex,
      pagesize: operationPagination.pagesize,
    }
    if (operationSearchForm.operationType) {
      params.operationType = operationSearchForm.operationType
    }
    if (operationSearchForm.operator) {
      params.operator = operationSearchForm.operator
    }
    if (operationSearchForm.operationTime?.length) {
      params.beginTime = operationSearchForm.operationTime[0]
      params.endTime = operationSearchForm.operationTime[1]
    }

    const apiCandidates = [
      '/api/SaleReturns/GetOperationRecords',
      '/api/OperationLog/GetOperationRecords',
      '/api/Log/GetOperationRecords',
      '/api/SaleReturns/GetSaleReturnsOperationLog',
    ]

    let success = false
    for (const apiPath of apiCandidates) {
      try {
        const res = await myaxios.get(apiPath, { params })
        if (res?.data?.code === 200) {
          const dataList = res.data.data?.data || res.data.data?.list || res.data.data || []

          const filteredList = dataList.filter((item: any) => {
            const moduleCode = item.moduleCode || item.module || item.businessModule
            const moduleName = item.moduleName || item.businessModuleName
            const documentType = item.documentType || item.businessType
            const docId = item.saleReturnsId || item.documentId || item.businessId || item.relatedId

            if (docId && String(docId) === String(saleReturnsForm.saleReturnsId)) {
              return true
            }

            const isSaleReturnsModule =
              moduleCode === 'SaleReturns' ||
              moduleName === '销售退货' ||
              documentType === 'SaleReturns' ||
              item.businessType === 'SaleReturns' ||
              item.module === 'SaleReturns'

            if (isSaleReturnsModule) {
              return true
            }

            const operationContent =
              item.operationContent || item.operateContent || item.actionDescription || item.description || item.content || ''
            if (operationContent && saleReturnsForm.saleReturnsNo && operationContent.includes(saleReturnsForm.saleReturnsNo)) {
              return true
            }
            return false
          })

          operationRecords.value = filteredList.map((item: any) => {
            let operationType = item.operationType || item.operateType || item.actionType || item.type || ''
            if (['更新', '编辑', 'Update', 'Edit'].includes(operationType)) {
              operationType = '修改'
            } else if (['新增', '创建', 'Create', 'Add'].includes(operationType)) {
              operationType = '新增'
            } else if (['删除', 'Delete', 'Remove'].includes(operationType)) {
              operationType = '删除'
            }

            let operationContent = item.operationContent || item.operateContent || item.actionDescription || item.description || item.content || ''
            if (!operationContent && operationType) {
              operationContent = `${operationType}销售退货单`
            }

            return {
              ...item,
              creator: item.creator || item.createor || item.documentMaker || item.maker || saleReturnsForm.createor || '',
              operator: item.operator || item.operateUser || item.userName || item.createUser || item.operateUserName || '',
              operationType,
              operationContent,
              operationTime: item.operationTime || item.operateTime || item.createTime || item.createrTime || item.operateDate || item.updateTime || '',
            }
          })
          operationPagination.total = res.data.data?.listCount || res.data.data?.total || operationRecords.value.length
          operationLoaded.value = true
          success = true
          break
        }
      } catch (err) {
        console.warn(`尝试接口 ${apiPath} 失败:`, err)
        continue
      }
    }

    if (!success) {
      console.warn('所有操作记录接口都不可用，使用空数据')
      operationRecords.value = []
      operationPagination.total = 0
    }
  } catch (error) {
    console.error('获取操作记录失败:', error)
    operationRecords.value = []
    operationPagination.total = 0
  } finally {
    operationLoading.value = false
  }
}

// 加载审核记录
const loadApprovalRecords = async () => {
  approvalLoading.value = true
  try {
    // TODO: 调用审核记录接口
    // const res = await myaxios.get('/api/SaleReturns/GetApprovalRecords', {
    //   params: { saleReturnsId: saleReturnsForm.saleReturnsId },
    // })
    // if (res?.data?.code === 200) {
    //   approvalRecords.value = res.data.data || []
    // }
    approvalRecords.value = []
  } catch (error) {
    console.error('获取审核记录失败:', error)
  } finally {
    approvalLoading.value = false
  }
}

// 操作记录相关
const handleOperationQuery = () => {
  operationPagination.pageindex = 1
  loadOperationRecords(true)
}

const handleOperationReset = () => {
  operationSearchForm.operationType = ''
  operationSearchForm.operator = ''
  operationSearchForm.operationTime = []
  operationPagination.pageindex = 1
  loadOperationRecords(true)
}

const handleOperationSizeChange = (size: number) => {
  operationPagination.pagesize = size
  loadOperationRecords(true)
}

const handleOperationPageChange = (page: number) => {
  operationPagination.pageindex = page
  loadOperationRecords(true)
}

// 导出功能
const handleExportDetails = () => {
  ElMessage.warning('导出功能正在开发中')
}

const handleExportInbound = () => {
  ElMessage.warning('导出功能正在开发中')
}

const handleExportOperation = () => {
  ElMessage.warning('导出功能正在开发中')
}

onMounted(async () => {
  const id = route.query.saleReturnsId as string
  if (!id) {
    ElMessage.error('缺少销售退货单ID')
    router.push('/getsalereturn')
    return
  }
  await loadSaleReturnsDetail(id)
  
  // 如果URL中有刷新操作记录的参数，自动加载操作记录
  if (route.query.refreshOperation === 'true') {
    activeTab.value = 'operation'
    setTimeout(() => {
      loadOperationRecords(true)
    }, 500)
  }
})
</script>

<style scoped>
.detail-page {
  padding: 16px;
  background: #f5f7fa;
  min-height: 100vh;
}

.detail-header {
  margin-bottom: 16px;
}

.detail-card {
  margin-bottom: 16px;
}

.info-card {
  background: #fff;
}

.tabs-card {
  background: #fff;
}

/* 顶部标题和操作区域 */
.header-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding-bottom: 20px;
  border-bottom: 1px solid #ebeef5;
}

.title-area {
  display: flex;
  align-items: center;
  gap: 12px;
}

.order-label {
  font-size: 14px;
  color: #606266;
  font-weight: 500;
}

.order-number {
  font-size: 20px;
  font-weight: 600;
  color: #303133;
}

.status-tag {
  margin-left: 8px;
}

.action-buttons {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.action-buttons .el-button {
  min-width: 70px;
}

/* 信息内容 */
.info-content {
  margin-top: 0;
}

.info-row {
  margin-top: 0;
}

.info-row :deep(.el-descriptions__table) {
  border-top: none;
}

.info-value {
  color: #303133;
  font-size: 14px;
  word-break: break-word;
}

:deep(.el-descriptions) {
  margin-bottom: 0;
}

:deep(.el-descriptions__label) {
  color: #909399;
  font-weight: 500;
  background-color: #fafafa;
  width: 120px;
  text-align: right;
  padding-right: 16px;
}

:deep(.el-descriptions__content) {
  color: #303133;
  background-color: #fff;
  padding-left: 16px;
}

:deep(.el-descriptions__table) {
  width: 100%;
}

:deep(.el-descriptions__table .el-descriptions__cell) {
  padding: 12px 0;
}

/* 标签页区域 */
.tabs-section {
  margin-top: 0;
}

.detail-tabs {
  margin-top: 0;
}

:deep(.el-tabs__content) {
  padding-top: 0;
}

.tab-content {
  padding: 20px 0;
}

.tab-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.search-form {
  margin-bottom: 16px;
}

/* 其他信息样式 */
.section-block {
  margin-bottom: 32px;
}

.section-block:last-child {
  margin-bottom: 0;
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  margin: 0 0 16px 0;
  padding-bottom: 8px;
  border-bottom: 2px solid #409eff;
}

.attachment-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.file-link {
  display: inline-flex;
  align-items: center;
  gap: 6px;
  padding: 8px 12px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  transition: all 0.2s;
}

.file-link:hover {
  border-color: #409eff;
  color: #409eff;
}

.empty-attachment {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px;
  color: #909399;
}

.attachment-icon {
  font-size: 48px;
  margin-bottom: 12px;
}

.empty-text {
  text-align: center;
  padding: 40px;
  color: #909399;
}

/* 汇总样式 */
.detail-summary {
  margin-top: 16px;
  padding: 12px 16px;
  background: #f9fafc;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  display: flex;
  gap: 24px;
  align-items: center;
  font-size: 14px;
  color: #606266;
}

.amount-text {
  font-weight: 600;
  color: #f56c6c;
  font-family: 'Courier New', monospace;
}

.pagination-wrapper {
  margin-top: 16px;
  display: flex;
  justify-content: flex-end;
}
</style>

